import pandas as pd
import numpy as np
import glob


# 获取作者名称和评分
def getNameGrade():
    # 打开csv文件
    file = pd.read_csv(r'books.csv')
    file1 = np.array(file)
    grade = []
    name = []
    # gradelist = []
    # 把姓名和评分提取出来
    for item in file1:
        name.append(item[0])
        grade.append(item[3])
    gradelist = pd.DataFrame({'姓名': name, '评分': grade})
    # 去除没有评分的作者
    grade1 = gradelist.dropna(axis=0, how='any')
    # 生成csv文件
    grade1.to_csv('grade.csv', index=None, encoding='utf-8')


# 按名称分组求和并计算每位作者的平均评分
def groupAndMean():
    # 读取作者名称和评分表
    df = pd.read_csv('grade.csv')
    # 将数据按人名分组求和并求平均数
    df_mean = df.groupby('姓名')['评分'].mean()
    # 生成csv文件
    df_mean.to_csv('grade_mean1.csv')
    df = pd.read_csv('grade_mean1.csv')
    df_largest = df.nlargest(20, '评分')
    print(df_largest)
    df_largest.to_csv('../../../Data/zhangjinyang/mean/grade_mean.csv', index=None, encoding='utf-8')


# 合并几个分类的csv文件
def mergeAll():
    # 获取文件名列表
    file_list = glob.glob('../../../Data/zhangjinyang/books_*.csv')

    # 读取每个文件并保存到DataFrame列表中
    df_list = []
    for i, file_name in enumerate(file_list):
        df = pd.read_csv(file_name)
        df_list.append(df)

    # 按行合并多个DataFrame
    df_merged = pd.concat(df_list, axis=0, ignore_index=True)
    df_merged.to_csv('books.csv', index=None, encoding='utf-8')


if __name__ == '__main__':
    mergeAll()
    getNameGrade()
    groupAndMean()
